using System.Collections.Generic;
using System.Linq;
using System;
using System.ServiceModel;

namespace Sogeti.Guidelines.WCF.Extensions
{
    public class InstanceItems
    {
        private readonly Dictionary<object, object> _items = new Dictionary<object, object>();

        public InstanceItems(ICommunicationObject context)
        {
            Hook(context);
        }

        public object Find(object key)
        {
            if (_items.ContainsKey(key))
                return _items[key];

            return null;
        }

        public void Set(object key, object value)
        {
            _items[key] = value;
        }

        public void Remove(object key)
        {
            _items.Remove(key);
        }

        public void CleanUp(object sender, EventArgs e)
        {
            foreach (var item in _items.Select(item => item.Value))
            {
                if (item is IDisposable)
                    ((IDisposable) item).Dispose();
            }
        }

        private void Hook(ICommunicationObject instanceContext)
        {
            instanceContext.Closed += CleanUp;
            instanceContext.Faulted += CleanUp;
        }
    }
}